//
//  STSegmentedControl.m
//  STSegmentedControl
//
//  Created by Cedric Vandendriessche on 10/11/10.
//  Copyright 2010 FreshCreations. All rights reserved.
//

#import "STSegmentedControl.h"

#import "UIStyleSkinManagerInternal.h"

#define IMG_SEGMENT_LEFT  @"segment_left.png"
#define IMG_SEGMENT_RIGHT @"segment_right.png"
#define IMG_SEGMENT_MIDDLE @"segment_middle.png"
#define IMG_SEGMENT_LEFT_SELECTED @"segment_left_selected.png"
#define IMG_SEGMENT_RIGHT_SELECTED @"segment_right_selected.png"
#define IMG_SEGMENT_MIDDLE_SELECTED @"segment_middle_selected.png"


@interface STSegmentedControl ()
{
    NSMutableArray *_segments;
	UIImage *_normalImageLeft;
	UIImage *_normalImageMiddle;
	UIImage *_normalImageRight;
	UIImage *_selectedImageLeft;
	UIImage *_selectedImageMiddle;
	UIImage *_selectedImageRight;
	NSUInteger _numberOfSegments;
	NSInteger _selectedSegmentIndex;
	BOOL _programmaticIndexChange;
	BOOL _momentary;
    UIColor* _selectedTextColor;
    UIColor* _normalTextColor;
    UIFont* _font;
    NSMutableArray* _arImage;
}

- (void)updateUI;
- (void)deselectAllSegments;
- (void)insertSegmentWithObject:(NSObject *)object atIndex:(NSUInteger)index;
- (void)setObject:(NSObject *)object forSegmentAtIndex:(NSUInteger)index;
@end

@implementation STSegmentedControl

@synthesize segments = _segments;
@synthesize numberOfSegments = _numberOfSegments;
@synthesize selectedSegmentIndex = _selectedSegmentIndex;
@synthesize momentary = _momentary;
@synthesize normalImageLeft = _normalImageLeft;
@synthesize normalImageMiddle = _normalImageMiddle;
@synthesize normalImageRight = _normalImageRight;
@synthesize selectedImageLeft = _selectedImageLeft;
@synthesize selectedImageMiddle = _selectedImageMiddle;
@synthesize selectedImageRight = _selectedImageRight;
@synthesize selectedTextColor = _selectedTextColor;
@synthesize normalTextColor = _normalTextColor;
@synthesize font = _font;
@synthesize arImage = _arImage;

#pragma mark -
#pragma mark Initializer

- (id)initWithFrame:(CGRect)frame 
{
    if((self = [super initWithFrame:frame]))
    {
		self.backgroundColor = [UIColor clearColor];
		
		/*
		 Set the standard images
		 */
		self.normalImageLeft = [UIImage imageNamed:IMG_SEGMENT_LEFT];
		self.normalImageMiddle = [UIImage imageNamed:IMG_SEGMENT_MIDDLE];
		self.normalImageRight= [UIImage imageNamed:IMG_SEGMENT_RIGHT];
		self.selectedImageLeft = [UIImage imageNamed:IMG_SEGMENT_LEFT_SELECTED] ;
		self.selectedImageMiddle = [UIImage imageNamed:IMG_SEGMENT_MIDDLE_SELECTED] ;
		self.selectedImageRight = [UIImage imageNamed:IMG_SEGMENT_RIGHT_SELECTED] ;
		
		_selectedSegmentIndex = STSegmentedControlNoSegment;
		_momentary = NO;
        
        CSTSegmentedStyleSkin* uiss=[CUIStyleSkinManager getSTSegmentedStyleSkin];
        self.selectedTextColor = uiss.selectedTextColor != nil ? uiss.selectedTextColor : [UIColor whiteColor];
        self.normalTextColor = uiss.normalTextColor != nil ? uiss.normalTextColor : [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1];
        self.font = [UIFont systemFontOfSize:12];
    }
    return self;
}

- (id)initWithItems:(NSArray *)items 
{
    if((self = [self initWithFrame:CGRectZero])) 
    {        
		self.segments = [NSMutableArray arrayWithArray:items];
    }
    return self;
}

#pragma mark -
#pragma mark initWithCoder for IB support

- (id)initWithCoder:(NSCoder *)decoder 
{
    if(self == [super initWithCoder:decoder]) 
    {
		self.backgroundColor = [UIColor clearColor];
		self.frame = self.frame;
		
		/*
		 Set the standard images
		 */
		_normalImageLeft = [[UIImage imageNamed:IMG_SEGMENT_LEFT] retain_mm];
		_normalImageMiddle = [[UIImage imageNamed:IMG_SEGMENT_MIDDLE] retain_mm];
		_normalImageRight= [[UIImage imageNamed:IMG_SEGMENT_RIGHT] retain_mm];
		_selectedImageLeft = [[UIImage imageNamed:IMG_SEGMENT_LEFT_SELECTED] retain_mm];
		_selectedImageMiddle = [[UIImage imageNamed:IMG_SEGMENT_MIDDLE_SELECTED] retain_mm];
		_selectedImageRight = [[UIImage imageNamed:IMG_SEGMENT_RIGHT_SELECTED] retain_mm];
		
		_selectedSegmentIndex = STSegmentedControlNoSegment;
		_momentary = NO;
        
        CSTSegmentedStyleSkin* uiss=[CUIStyleSkinManager getSTSegmentedStyleSkin];
        self.selectedTextColor = uiss.selectedTextColor != nil ? uiss.selectedTextColor : [UIColor whiteColor];
        self.normalTextColor = uiss.normalTextColor != nil ? uiss.normalTextColor : [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1];
        self.font = [UIFont systemFontOfSize:12];
	}
	
    return self;
}

-(void)setArImage:(NSMutableArray *)arImage
{
    self.normalImageLeft=nil;
    self.normalImageMiddle=nil;
    self.normalImageRight=nil;
    self.selectedImageLeft=nil;
    self.selectedImageMiddle=nil;
    self.selectedImageRight=nil;
    [_arImage release_mm];
    _arImage = [arImage retain_mm];
}

-(NSMutableArray*)arImage
{
    return _arImage;
}

#pragma mark -

- (void)updateUI 
{
	/*
	 Remove every UIButton from screen
	 */
	[[self subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
	
	/*
	 We're only displaying this element if there are at least two buttons
	 */
//	if([segments count] > 1)
//	{
		_numberOfSegments = [_segments count];
		int indexOfObject = 0;
		
		float segmentWidth = (float)self.frame.size.width / _numberOfSegments;
		float lastX = 0.0;
		
		for(NSObject *object in _segments)
		{
			/*
			 Calculate the frame for the current segment
			 */
			int currentSegmentWidth; 
			
			if(indexOfObject < _numberOfSegments - 1)
				currentSegmentWidth = round(lastX + segmentWidth) - round(lastX) + 1;
			else
				currentSegmentWidth = round(lastX + segmentWidth) - round(lastX);
			
			CGRect segmentFrame = CGRectMake(round(lastX), 0, currentSegmentWidth, self.frame.size.height);
			lastX += segmentWidth;
			
			/*
			 Give every button the background image it needs for its current state
			 */
			UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
			
            if(_arImage==nil)
            {
                if(indexOfObject == 0)
                {
                    if(_selectedSegmentIndex == indexOfObject)
                        [button setBackgroundImage:[_selectedImageLeft resizeableCenterImage] forState:UIControlStateNormal];
                    else
                        [button setBackgroundImage:[_normalImageLeft resizeableCenterImage] forState:UIControlStateNormal];
                }
                else if(indexOfObject == _numberOfSegments - 1)
                {
                    if(_selectedSegmentIndex == indexOfObject)
                        [button setBackgroundImage:[_selectedImageRight resizeableCenterImage] forState:UIControlStateNormal];
                    else
                        [button setBackgroundImage:[_normalImageRight resizeableCenterImage] forState:UIControlStateNormal];
                }
                else
                {
                    if(_selectedSegmentIndex == indexOfObject)
                        [button setBackgroundImage:[_selectedImageMiddle resizeableCenterImage] forState:UIControlStateNormal];
                    else
                        [button setBackgroundImage:[_normalImageMiddle resizeableCenterImage] forState:UIControlStateNormal];
                }
            }
            else if(_arImage.count>0)
            {
                NSDictionary* dic=[_arImage objectAtIndex:indexOfObject];
                if(_selectedSegmentIndex == indexOfObject)
                    [button setBackgroundImage:[[dic objectForKey:STSegmentedControlSelectedImage] resizeableCenterImage] forState:UIControlStateNormal];
                else
                    [button setBackgroundImage:[[dic objectForKey:STSegmentedControlNormalImage] resizeableCenterImage] forState:UIControlStateNormal];
            }
			
			button.frame = segmentFrame;
			button.titleLabel.font = _font;
			button.tag = indexOfObject + 1;
			button.adjustsImageWhenHighlighted = NO;
            [button setTitleColor:_selectedSegmentIndex==indexOfObject?_selectedTextColor:_normalTextColor forState:UIControlStateNormal];
			
			/*
			 Check if we're dealing with a string or an image
			 */
			if([object isKindOfClass:[NSString class]])
			{
				[button setTitle:(NSString *)object forState:UIControlStateNormal];
			}
			else if([object isKindOfClass:[UIImage class]])
			{
				[button setImage:(UIImage *)object forState:UIControlStateNormal];
			}
			
			[button addTarget:self action:@selector(segmentTapped:) forControlEvents:UIControlEventTouchDown];
			[self addSubview:button];
			
			++indexOfObject;
//		}
		
		/*
		 Make sure the selected segment shows both its separators
		 */
		[self bringSubviewToFront:[self viewWithTag:_selectedSegmentIndex + 1]];
	}
}

- (void)deselectAllSegments {
	/*
	 Deselects all segments
	 */
	for(UIButton *button in self.subviews)
	{
        [button setTitleColor:_normalTextColor forState:UIControlStateNormal];
        
        if(_arImage==nil)
        {
            if(button.tag == 1)
            {
                [button setBackgroundImage:[_normalImageLeft resizeableCenterImage] forState:UIControlStateNormal];
            }
            else if(button.tag == _numberOfSegments)
            {
                [button setBackgroundImage:[_normalImageRight resizeableCenterImage] forState:UIControlStateNormal];
            }
            else
            {
                [button setBackgroundImage:[_normalImageMiddle resizeableCenterImage] forState:UIControlStateNormal];
            }
        }else if(_arImage.count>0)
        {
            NSDictionary* dic=[_arImage objectAtIndex:button.tag-1];
            [button setBackgroundImage:[[dic objectForKey:STSegmentedControlNormalImage] resizeableCenterImage] forState:UIControlStateNormal];
        }
	}
}

- (void)resetSegments 
{
	/*
	 Reset the index and send the action
	 */
	_selectedSegmentIndex = STSegmentedControlNoSegment;
	[self sendActionsForControlEvents:UIControlEventValueChanged];
	
	[self updateUI];
}

-(void)segmentTapped:(id)sender sendaction:(BOOL)bAction
{
	[self deselectAllSegments];
	
	/*
	 Send the action
	 */
	UIButton *button = sender;
	[self bringSubviewToFront:button];
    
    [button setTitleColor:_selectedTextColor forState:UIControlStateNormal];
	
	if(_selectedSegmentIndex != button.tag - 1 || _programmaticIndexChange)
	{
		_selectedSegmentIndex = button.tag - 1;
		_programmaticIndexChange = NO;
        if(bAction==YES)
            [self sendActionsForControlEvents:UIControlEventValueChanged];
	}
	
	/*
	 Give the tapped segment the selected look
	 */
    if(_arImage==nil)
    {
        if(button.tag == 1)
        {
            [button setBackgroundImage:[_selectedImageLeft resizeableCenterImage] forState:UIControlStateNormal];
        }
        else if(button.tag == _numberOfSegments)
        {
            [button setBackgroundImage:[_selectedImageRight resizeableCenterImage] forState:UIControlStateNormal];
        }
        else
        {
            [button setBackgroundImage:[_selectedImageMiddle resizeableCenterImage] forState:UIControlStateNormal];
        }
    }else if(_arImage.count>0)
    {
        NSDictionary* dic=[_arImage objectAtIndex:button.tag-1];
        [button setBackgroundImage:[[dic objectForKey:STSegmentedControlSelectedImage] resizeableCenterImage] forState:UIControlStateNormal];
    }
	
	if(_momentary)
		[self performSelector:@selector(deselectAllSegments) withObject:nil afterDelay:0.2];
}

- (void)segmentTapped:(id)sender
{
	[self segmentTapped:sender sendaction:YES];
}

#pragma mark -
#pragma mark Manipulation methods

- (void)insertSegmentWithObject:(NSObject *)object atIndex:(NSUInteger)index {
	/*
	 Making sure we don't call out of bounds
	 */
	if(index <= _numberOfSegments && index > -1)
	{
		[_segments insertObject:object atIndex:index];
		[self resetSegments];
	}
}

- (void)setObject:(NSObject *)object forSegmentAtIndex:(NSUInteger)index {
	/*
	 Making sure we don't call out of bounds
	 */
	if(index < _numberOfSegments && index > -1)
	{
		[_segments replaceObjectAtIndex:index withObject:object];
		[self resetSegments];
	}
}

#pragma mark -

- (void)insertSegmentWithTitle:(NSString *)title atIndex:(NSUInteger)index
{
	[self insertSegmentWithObject:title atIndex:index];	
}

- (void)insertSegmentWithImage:(NSString *)image atIndex:(NSUInteger)index
{
	[self insertSegmentWithObject:image atIndex:index];		
}

- (void)removeSegmentAtIndex:(NSUInteger)index
{
	/*
	 Making sure we don't call out of bounds
	 If you delete a segment when only having two segments, the control won't be shown anymore
	 */
	if(index < _numberOfSegments && index >-1)
	{
		[_segments removeObjectAtIndex:index];
		[self resetSegments];
	}
}

- (void)removeAllSegments
{
	[_segments removeAllObjects];
	
	_selectedSegmentIndex = STSegmentedControlNoSegment;
	[self updateUI];
}

- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)index
{
	[self setObject:title forSegmentAtIndex:index];
}

- (void)setImage:(NSString *)image forSegmentAtIndex:(NSUInteger)index
{
	[self setObject:image forSegmentAtIndex:index];
}

#pragma mark -
#pragma mark Getters

- (NSString *)titleForSegmentAtIndex:(NSUInteger)index
{
	if(index < [_segments count])
	{
		if([[_segments objectAtIndex:index] isKindOfClass:[NSString class]])
		{
			return [_segments objectAtIndex:index];
		}
	}
	
	return nil;
}

- (UIImage *)imageForSegmentAtIndex:(NSUInteger)index
{
	if(index < [_segments count])
	{
		if([[_segments objectAtIndex:index] isKindOfClass:[UIImage class]])
		{
			return [_segments objectAtIndex:index];
		}
	}
	
	return nil;
}

#pragma -
#pragma mark Setters

- (void)setSegments:(NSArray *)array
{
    [_segments release_mm];
    _segments = [NSMutableArray new];
    [_segments addObjectsFromArray:array];
    [self resetSegments];
}

- (void)setSelectedSegmentIndex:(NSInteger)index
{
	if(index != _selectedSegmentIndex)
	{
		_selectedSegmentIndex = index;
		_programmaticIndexChange = YES;
		
		if(index >= 0 && index < _numberOfSegments)
		{
			UIButton *button = (UIButton *)[self viewWithTag:index + 1];
			[self segmentTapped:button sendaction:NO];
		}
	}
}

-(void)setSelectedSegmentIndexValueChange:(int)nIndex
{
    if(nIndex != _selectedSegmentIndex)
	{
		_selectedSegmentIndex = nIndex;
		_programmaticIndexChange = YES;
		
		if(nIndex >= 0 && nIndex < _numberOfSegments)
		{
			UIButton *button = (UIButton *)[self viewWithTag:nIndex + 1];
			[self segmentTapped:button sendaction:YES];
		}
	}
}

- (void)setFrame:(CGRect)rect 
{
    BOOL b=NO;
    if(self.width!=rect.size.width||self.height!=rect.size.height)
        b=YES;
	[super setFrame:rect];
    if(b==YES)
        [self updateUI];
}

#pragma mark -
#pragma mark Image setters

- (void)setNormalImageLeft:(UIImage *)image
{
	if(image != _normalImageLeft)
	{
		[_normalImageLeft release_mm];
		_normalImageLeft = [image retain_mm];
	
		[self updateUI];
	}
}

- (void)setNormalImageMiddle:(UIImage *)image
{
	if(image != _normalImageMiddle)
	{
		[_normalImageMiddle release_mm];
		_normalImageMiddle = [image retain_mm];
	
		[self updateUI];
	}
}

- (void)setNormalImageRight:(UIImage *)image
{
	if(image != _normalImageRight)
	{
		[_normalImageRight release_mm];
		_normalImageRight = [image retain_mm];
	
		[self updateUI];
	}
}

- (void)setSelectedImageLeft:(UIImage *)image
{
	if(image != _selectedImageLeft)
	{
		[_selectedImageLeft release_mm];
		_selectedImageLeft = [image retain_mm];
	
		[self updateUI];
	}
}

- (void)setSelectedImageMiddle:(UIImage *)image
{
	if(image != _selectedImageMiddle)
	{
		[_selectedImageMiddle release_mm];
		_selectedImageMiddle = [image retain_mm];
	
		[self updateUI];
	}
}

- (void)setSelectedImageRight:(UIImage *)image
{
	if(image != _selectedImageRight)
	{
		[_selectedImageRight release_mm];
		_selectedImageRight = [image retain_mm];
	
		[self updateUI];
	}
}

#pragma mark -

- (void)dealloc
{
    [_arImage release_mm];
	[_segments release_mm];
	[_normalImageLeft release_mm];
	[_normalImageMiddle release_mm];
	[_normalImageRight release_mm];
	[_selectedImageLeft release_mm];
	[_selectedImageMiddle release_mm];
	[_selectedImageRight release_mm];
    [_selectedTextColor release_mm];
    [_normalTextColor release_mm];
    [_font release_mm];
	superdealloc_mm;
}

@end
